package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.db.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;

/**
 * @author cx
 * @date 2023/4/2 21:54
 * @Version 1.0
 */
@Service
public class WxStorageServiceImpl implements WxStorageService{
    @Autowired
    MarketStorageMapper storageMapper;
    @Override
    public MarketStorage update(MultipartFile file, HttpServletRequest req) {
        MarketStorage result;

        MarketStorage storage = new MarketStorage();

        String fileName = file.getOriginalFilename();
        String key = fileName;
        String contentType = file.getContentType();
        long size = file.getSize();

        //文件存储在D:/image/
        String relativePath = "image/" + key;
        String image = req.getServletContext().getRealPath(relativePath);
        File f = new File(image);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        //file.write(image);
        storage.setName(fileName);
        storage.setKey(key);
        storage.setType(contentType);
        storage.setSize((int) size);
        storage.setUrl("http://localhost:8083/" + relativePath);
        storage.setUpdateTime(LocalDateTime.now());
        storage.setAddTime(LocalDateTime.now());
        storage.setDeleted(false);
        storageMapper.insertSelective(storage);
        Integer id = storage.getId();
        result = storageMapper.selectByPrimaryKey(id);

        try {
            //存储到数据库
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
